package com.twotiger.and.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import app.twotiger.p2p.R;
import cn.jpush.android.api.JPushInterface;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.readystatesoftware.systembartint.SystemBarTintManager.SystemBarConfig;
import com.twotiger.and.Constants;
import com.twotiger.and.activity.base.BaseActivity;
import com.twotiger.and.activity.base.BaseFragment;
import com.twotiger.and.activity.base.BaseHandler;
import com.twotiger.and.activity.current.CurrentHost;
import com.twotiger.and.activity.user.LockActivity;
import com.twotiger.and.activity.user.LoginPage;
import com.twotiger.and.bean.Basebean;
import com.twotiger.and.bean.ImageBean;
import com.twotiger.and.bean.ImageList;
import com.twotiger.and.bean.Jpushbean;
import com.twotiger.and.bean.Jpushbean2;
import com.twotiger.and.bean.Update;
import com.twotiger.and.bean.User;
import com.twotiger.and.db.dao.JpushNoticeDao;
import com.twotiger.and.util.ListUtils;
import com.twotiger.and.util.LogUtil;
import com.twotiger.and.util.PackageUtils;
import com.twotiger.and.util.PreferencesUtils;
import com.twotiger.and.util.PromptManager;
import com.twotiger.and.util.ScreenListener;
import com.twotiger.and.util.StringUtils;
import com.twotiger.and.util.UpdateVersionUtil;
import com.umeng.analytics.MobclickAgent;

/**
 * 
 * @Description: 
 *  主activity、包含4个页面<BR/>
 *  打开特定页面方式：
 *  intent.putExtra("BUTTON",页面按钮ID);
 * @Author douxy
 * @Date 2015年8月10日 下午3:24:27
 */
@SuppressLint("HandlerLeak")
public class HomeActivity extends BaseActivity implements View.OnClickListener {

    /**
     * hander code
     */
    private static final int PULL_UPDATA_INFO_SUCCES = 0;
    private static final int PULL_UPDATA_INFO_FAILED = 1;

    private final static int GET_USERINFO_SSUCESS = 2;
    private final static int GET_USERINFO_FAIL = 3;

    protected static final int GETPOPIMAGSUCCESS = 4;
    private static final int GETPOPIMAGFAILURE = 5;

    private RadioGroup bottom_menu;
    public FragmentManager mainFragmentManager;
    /**当前显示fragment*/
    private static int currentBtn = 0;

    private ScreenListener screenListener;
    private HashMap<String, String> params;
    private int system_upgrade_tag; //系统维护中
    private View view;

    @Override
    protected void setListener() {
        handler = new BaseHandler(this) {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case GETPOPIMAGSUCCESS:
                    Basebean result = JSON.parseObject((String) msg.obj, Basebean.class);
                    if (result.isOk()) {
                        ImageList imageList = JSON.parseObject(result.data, ImageList.class);
                        List<ImageBean> list = JSON
                            .parseArray(imageList.getList(), ImageBean.class);
                        if (!ListUtils.isEmpty(list)) {
                            List<ImageBean> needShowList = prePareList(list);
                            if (needShowList.size() > 0) {
                                PromptManager.showHomePop(mContext, needShowList);
                            }
                        }
                    }
                    break;
                case GETPOPIMAGFAILURE:

                    break;
                case GET_USERINFO_SSUCESS:
                    Basebean result_1 = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_1.isOk()) {
                        User user = JSON.parseObject(result_1.data, User.class);
                        application.setUser(user);
                    }
                    break;
                case GET_USERINFO_FAIL:

                    break;
                case PULL_UPDATA_INFO_SUCCES:
                    Basebean result_up = JSONObject.parseObject((String) msg.obj, Basebean.class);
                    if (result_up.isOk()) {
                        Basebean responseinfo = JSONObject
                                .parseObject(result_up.data, Basebean.class);
                        Update update = JSONObject.parseObject((String) msg.obj, Update.class);
                        if (update.getId() != null && !"null".equals(update.getId())) {
                            if (Integer.parseInt(update.getId()) > PackageUtils
                                .getAppVersionCode(mContext)) {
                                UpdateVersionUtil
                                    .ShowUpAppDialog(mContext, update.getDownloadURL());
                            } else {

                            }
                        }
                    } else {
                        PromptManager.showConfirmAlert(mContext, result_up.codeDesc);
                    }

                    break;
                case PULL_UPDATA_INFO_FAILED:

                    break;
                //                case TIME_TO_VAILD_GESTURE:
                //                    if (needValidGesture()) {
                //                        Intent intent = new Intent(HomeActivity.this, LockActivity.class);
                //                        startActivity(intent);
                //                        overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.silent_anim);
                //                    }
                //                    break;
                default:
                    break;
                }
                super.handleMessage(msg);
            }
        };
        bottom_menu.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (system_upgrade_tag == BaseHandler.SYSTEM_UPGRADE) {
                    replaceFragment(BaseHandler.SYSTEM_UPGRADE, null, false);
                } else {
                    changeFragment(checkedId, null, false);
                }
                switch (checkedId) {
                case R.id.radio_btn1:
                    MobclickAgent.onEvent(mContext, Constants.UMENG_EVENT_JINGXUAN);
                    break;
                case R.id.radio_btn2:
                    MobclickAgent.onEvent(mContext, Constants.UMENG_EVENT_PROJECT);
                    break;
                case R.id.radio_btn3:
                    MobclickAgent.onEvent(mContext, Constants.UMENG_EVENT_CURRENT);
                    break;
                case R.id.radio_btn4:
                    MobclickAgent.onEvent(mContext, Constants.UMENG_EVENT_ACCOUNT);
                    break;
                default:
                    break;
                }
            }
        });
    }

    /**
     * 活动展示次数策略(更新list中活动需要展示的次数，同时更新sp存储)
     * 
     * @param list
     * @return
     */
    protected List<ImageBean> prePareList(List<ImageBean> list) {
        List<ImageBean> newList = new ArrayList<ImageBean>(); //临时集合，存储需要remove的元素

        for (int i = 0; i < list.size(); i++) {
            int viewCountPre = PreferencesUtils.getIntBySPName(mContext,
                PreferencesUtils.PREFERENCE_NAME_POP_ACTIVITY, list.get(i).getImgId(), -1);
            if (viewCountPre != -1) {
                if (viewCountPre >= Integer.parseInt(list.get(i).getViewCount())) {
                    newList.add(list.get(i));
                } else {
                    viewCountPre++;
                    PreferencesUtils.putIntBySPName(mContext,
                        PreferencesUtils.PREFERENCE_NAME_POP_ACTIVITY, list.get(i).getImgId(),
                        viewCountPre);
                }
            } else {
                PreferencesUtils.putIntBySPName(mContext,
                    PreferencesUtils.PREFERENCE_NAME_POP_ACTIVITY, list.get(i).getImgId(), 1);
            }
        }

        //无需展示的，元素移除
        for (int i = 0; i < newList.size(); i++) {
            list.remove(newList.get(i));
        }
        return list;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CurrentHost.CURRENTREQUEST) {
            if (resultCode == CurrentHost.CURRENTRESULTCLOSE_SUC) {
                Intent intent = new Intent();
                intent.setClass(HomeActivity.this, CurrentHost.class);
                startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
            }
        }
    }

    @Override
    protected void onResume() {

        if (system_upgrade_tag == -1) {
            system_upgrade_tag = getIntent().getIntExtra("SYSTEM_UPGRADE", -1);
        }

        if (system_upgrade_tag == BaseHandler.SYSTEM_UPGRADE) {
            replaceFragment(BaseHandler.SYSTEM_UPGRADE, null, false);
            getIntent().removeExtra("SYSTEM_UPGRADE");
        } else {
            int toFragment = bottom_menu.getCheckedRadioButtonId();
            int tmp = getIntent().getIntExtra("BUTTON", toFragment);
            if (tmp > 0 && tmp != toFragment) {//需要更换当前显示页面
                ((RadioButton) (bottom_menu.findViewById(tmp))).setChecked(true);
                getIntent().removeExtra("BUTTON");
            } else {
                changeFragment(toFragment, null, false);
            }
        }

        super.onResume();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    private Jpushbean2 parscoustommsg(Context context, String msg, String title) {

        try {
            Jpushbean2 jpushbean = JSON.parseObject(msg, Jpushbean2.class);
            jpushbean.setName(title);
            return jpushbean;
        } catch (Exception e) {
            LogUtil.info(e.toString());
        }

        return null;
    }

    /**
     * 获取用户信息
     */
    private void getuserinfo() {
        params.clear();
        params.put("token", getToken());
        getDate(params, Constants.USERINFOQUERY, handler, GET_USERINFO_SSUCESS, GET_USERINFO_FAIL,
            false, false, false);
    }

    @Override
    protected void processLogic() {
        
        //设置状态栏文字颜色为黑色
//        setStatusBarBlack(this.getWindow(), true);

        params = getParm();

        //是否为系统维护（intent）
        system_upgrade_tag = getIntent().getIntExtra("SYSTEM_UPGRADE", -1);

        //启动计数
        application.otherService.startCount();
        //绑定服务
        //        startService(new Intent(this, LoctionService.class));
        if (mainFragmentManager == null) {
            mainFragmentManager = getSupportFragmentManager();
        }

        if (system_upgrade_tag != BaseHandler.SYSTEM_UPGRADE) {
            initScreenListener();

            // 检查版本更新 有新版本才提示
            checkUpdate();
            //如果用户已登录，请求用户信息，并更新本地信息
            getuserinfo();
            //请求检查是否有活动弹窗
            getPop();

            LogUtil.info("Registration_home ID:" + JPushInterface.getRegistrationID(mContext));
            //            JPushInterface.clearAllNotifications(getApplicationContext()); //清除通知栏消息

            //推送消息
            if (getIntent().getSerializableExtra("PUSH") != null) {
                final Jpushbean2 jpushbean2 = (Jpushbean2) getIntent().getSerializableExtra("PUSH");

                if (jpushbean2 != null && "link".equals(jpushbean2.getType())) {
                    if ("alert".equals(jpushbean2.getStyle())) {
                        cleanJpush(HomeActivity.this);
                        Intent intent = new Intent(HomeActivity.this, WebViewDialogPage.class);
                        intent.putExtra("PUSH", jpushbean2);
                        startNewActivity(intent, 0, 0, false);
                    } else if ("default".equals(jpushbean2.getStyle())) {
                        cleanJpush(HomeActivity.this);
                        Intent intent = new Intent(HomeActivity.this, WebViewPage.class);
                        intent.putExtra("url", jpushbean2.getTarget());
                        intent.putExtra("title", jpushbean2.getName());
                        intent.putExtra("PUSH", jpushbean2);
                        intent.putExtra("BACK_MODE", WebViewPage.BACK_DIRECT);
                        startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                    }
                } else if (jpushbean2 != null && "action".equals(jpushbean2.getType())) { //暂时不处理
                    //                    pushlogic(jpushbean);
                }

            } else {
                JpushNoticeDao jpushNoticeDao = new JpushNoticeDao(HomeActivity.this);
                List<String[]> jpushNotice_list = jpushNoticeDao.queryAll();
                if (!ListUtils.isEmpty(jpushNotice_list)) {

                    int notifactionId = Integer.parseInt(jpushNotice_list.get(0)[0]);
                    String notifactionAlert = jpushNotice_list.get(0)[1];
                    String notifactionTitle = jpushNotice_list.get(0)[2];
                    String notifactionContent = jpushNotice_list.get(0)[3];
                    Jpushbean2 jpushbean2 = parscoustommsg(HomeActivity.this, notifactionContent,
                        notifactionTitle);

                    if (jpushbean2 != null && "link".equals(jpushbean2.getType())) {
                        if ("alert".equals(jpushbean2.getStyle())) {
                            cleanJpush(HomeActivity.this);
                            //将本条通知在通知栏消失  
                            JPushInterface.clearNotificationById(getApplicationContext(),
                                notifactionId);
                            Intent intent = new Intent(HomeActivity.this, WebViewDialogPage.class);
                            intent.putExtra("PUSH", jpushbean2);
                            startNewActivity(intent, 0, 0, false);
                        } else if ("default".equals(jpushbean2.getStyle())) {
                            cleanJpush(HomeActivity.this);
                            //                            Intent intent = new Intent(HomeActivity.this, WebViewPage.class);
                            //                            intent.putExtra("url", jpushbean2.getTarget());
                            //                            intent.putExtra("title", jpushbean2.getName());
                            //                            intent.putExtra("PUSH", jpushbean2);
                            //                            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
                        }
                    } else if (jpushbean2 != null && "action".equals(jpushbean2.getType())) { //暂时不处理

                    }
                }
            }
        }
    }

    private void getPop() {
        params.clear();
        params.put("type", "popPage");
        getDate(params, Constants.IMGQUERY, handler, GETPOPIMAGSUCCESS, GETPOPIMAGFAILURE, false,
            false, false);
    }

    /**
     * 清除数据库保存的推送消息
     * 
     * @param context
     */
    private void cleanJpush(Context context) {
        JpushNoticeDao jpushNoticeDao = new JpushNoticeDao(context);
        jpushNoticeDao.deleteNotice(); //清除数据库数据
    }

    private void checkUpdate() {
        params.clear();
        params.put("type", "android");
        getDate(params, Constants.UPDATE, handler, PULL_UPDATA_INFO_SUCCES,
            PULL_UPDATA_INFO_FAILED, false, false, false);
    }

    /**
     * 推送逻辑处理
     * @param jpushbean
     */
    private void pushlogic(Jpushbean jpushbean) {
        if (jpushbean.getType().equals("link")) {
            Intent intent = new Intent(mContext, WebViewPage.class);
            intent.putExtra("title", jpushbean.getTitle());
            intent.putExtra("url", jpushbean.getTarget());
            startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
        } else {
            try {
                Class<?> pushclass = getClassLoader().loadClass(jpushbean.getTarget());
                Intent intent = new Intent(mContext, pushclass);
                intent.putExtra("id", jpushbean.getId());
                startNewActivity(intent, R.anim.push_left_in, R.anim.push_left_out, false);
            } catch (ClassNotFoundException e) {
                LogUtil.info("未知的类");
                e.printStackTrace();
            }
        }
    }

    private void initScreenListener() {
        screenListener = new ScreenListener(this);
        screenListener.begin(new ScreenListener.ScreenStateListener() {

            @Override
            public void onUserPresent() {// 解锁
                LogUtil.info("onUserPresent-->onUserPresent");
            }

            @Override
            public void onScreenOn() { //
                LogUtil.info("onScreenOn-->onScreenOn");
            }

            @Override
            public void onScreenOff() {
                LogUtil.info("onScreenOff-->onScreenOff");
                if (!StringUtils.isEmpty(PreferencesUtils.getString(HomeActivity.this,
                    Constants.gesture_psd))) {
                    Intent intent = new Intent(HomeActivity.this, LockActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (screenListener != null) {
            screenListener.unregisterListener();
        }
    }

    @Override
    public void onClick(View v) {

    }

    /**
     * 替换fragment（用于系统升级中的情况，将正常fragment）
     * 
     * @param fragmentId
     * @param bundle
     * @param isAddToBackStackAndShowBack
     */
    public void replaceFragment(int fragmentId, Bundle bundle, boolean isAddToBackStackAndShowBack) {
        BaseFragment toFragment = FragmentFactory.getInstanceByBtnID(fragmentId);
        BaseFragment fromFragment = FragmentFactory.getInstanceByBtnID(currentBtn);
        FragmentTransaction ft = mainFragmentManager.beginTransaction();
        if (bundle != null) {
            toFragment.setArguments(bundle);
        }
        if (toFragment != null) {
            if (fromFragment != null) {
                ft.remove(fromFragment);
            }
            if (!toFragment.isAdded() && toFragment.getTag() == null) {
                ft.replace(R.id.main_fragment, toFragment);
            }
        }

        if (isAddToBackStackAndShowBack) {
            ft.addToBackStack(null);
        }
        ft.commitAllowingStateLoss();
    }

    /**
     * 切换Fragment
     *
     * @param isAddToBackStackAndShowBack 是否添加到返回栈
     * @param bundle                      界面间传递数据
     * @param targetFragment              切换目标Fragment
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public void changeFragment(int fragmentId, Bundle bundle, boolean isAddToBackStackAndShowBack) {
        BaseFragment toFragment = FragmentFactory.getInstanceByBtnID(fragmentId);
        if (toFragment == null) {
            return;
        }

        //fromFragment 可能为null
        BaseFragment fromFragment = FragmentFactory.getInstanceByBtnID(currentBtn);

        String toTag = toFragment.getClass().getSimpleName();
        //String fromTag = fromFragment.getClas s().getSimpleName();
        LogUtil.info(HomeActivity.class, mainFragmentManager.toString());
        //需要登录、但未登录
        if (toFragment.isNeedLogin() && !isLogin()) {
            LogUtil.info(HomeActivity.class, "changeFragment need login");
            Intent intent = new Intent(mContext, LoginPage.class);
            intent.putExtra("FROM", fragmentId);
            //保留之前视图
            ((RadioButton) (bottom_menu.findViewById(currentBtn))).setChecked(true);
            startActivity(intent);
            overridePendingTransition(R.anim.slide_in_from_bottom, R.anim.silent_anim);
            return;
        }
        FragmentTransaction ft = mainFragmentManager.beginTransaction();
        if (bundle != null) {
            toFragment.setArguments(bundle);
        }
        /**
         * 如果要切换到的Fragment没有被Fragment事务添加，则隐藏被切换的Fragment，添加要切换的Fragment
         * 否则，则隐藏被切换的Fragment，显示要切换的Fragment
         * 
         */
        if (!toFragment.isAdded() && toFragment.getTag() == null) {
            ft.add(R.id.main_fragment, toFragment, toTag);
        } else {
            //note:
            //重建样式、使用baseFragment onHiddenChanged 替代
            //toFragment.rebuildTitleStyle();
            //toFragment.reloadData();
        }
        if (fromFragment != null && fromFragment.isAdded()) {
            ft.hide(fromFragment);
        }
        ft.show(toFragment);
        LogUtil.info("ttotoot:" + toFragment.toString());
        currentBtn = fragmentId;
        if (isAddToBackStackAndShowBack) {
            ft.addToBackStack(null);
        }
        ft.commitAllowingStateLoss();
    }

    @Override
    protected View loadViewLayout(LayoutInflater inflater) {
        view = inflater.inflate(R.layout.home_layout, null);
        return view;
    }
    
    /**
     * layout布局是从屏幕状态栏的顶部开始绘制还是从状态栏底部开始绘制
     * 
     * @param isFitStatusBar
     */
    public void setLayoutPadding(boolean isFitStatusBar){
        SystemBarConfig config = tintManager.getConfig();
        view.setPadding(0, isFitStatusBar ? 0 : config.getPixelInsetTop(false), 0, config.getPixelInsetBottom());
    }

    @Override
    protected void findViewById(View view) {
        bottom_menu = (RadioGroup) view.findViewById(R.id.bottom_menu);
    }

    @Override
    protected void onBackPress() {

    }

    @Override
    protected void onPause() {
        super.onPause();
        LogUtil.info(HomeActivity.class, "onPause");
        if (system_upgrade_tag != BaseHandler.SYSTEM_UPGRADE) {
            //暂停fragment
            FragmentFactory.getInstanceByBtnID(currentBtn).onPause();
        }
    }

}
